package com.hc.pokemen.feature_pokemen.presentation.pokemon_detail

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hc.pokemen.feature_pokemen.domain.repository.PokemonRepository
import com.hc.pokemen.feature_pokemen.domain.util.Resource
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class PokemonDetailViewModel @Inject constructor(private val repository: PokemonRepository) :
    ViewModel() {

    var state by mutableStateOf(PokemonDetailState())
        private set

    var effect = MutableSharedFlow<PokemonDetailEffect>()


    fun onEvent(event: PokemonDetailEvent) {
        when (event) {
            PokemonDetailEvent.BackClick -> {
                viewModelScope.launch {
                    effect.emit(PokemonDetailEffect.BackPokemonList)
                }
            }
        }
    }

    fun getPokemonInfo(name: String) {
        viewModelScope.launch {
            when (val resource = repository.getPokemon(name = name)) {
                is Resource.Error -> {
                    Log.d("CH", "Error")
                }

                is Resource.Success -> {
                    Log.d("CH", "Success")
                    state = state.copy(isLoading = false, pokemon = resource.data)
                }
            }
        }
    }
}